﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FAP_Login;
using log4net;
using FAP.Login;
using Microsoft.Win32;
using System.Diagnostics;
using FAP.DataAccess;
using System.Net;
using FAP.DataAccess.BLL;
using FAP.UserControls;

namespace FAP.UserControls
{
    public partial class LoginerUserControl : UserControl
    {

        private int proccess_percent = 0;
        List<taikhoan> lst_taikhoan = new List<taikhoan>();
        private ILog m_log = LogManager.GetLogger(typeof(LoginerUserControl));
        public LoginerUserControl()
        {
            InitializeComponent();

        }

        public void Refresh()
        {
            lv_Account_List.Items.Clear();
            //FAP.DataAccess.FAPDataContext context = new FAP.DataAccess.FAPDataContext();
            {
                m_log.Info("Load danh sách tài khoản về listview");
                //lst_taikhoan = context.taikhoans.Where(m => m.websiteid != null).ToList();
                lst_taikhoan = taikhoan.taikhoanSelectAll().ToList();
                //lst_taikhoan = taikhoan.taikhoanSelectRowByForeignKey_websiteid(1).ToList();
                if (lst_taikhoan == null)
                {
                    m_log.Warn("Khong co du lieu tai khoan");
                    return;
                }
                int stt = 1;
                lv_Account_List.Columns.Add("STT");
                lv_Account_List.Columns.Add("ID");
                lv_Account_List.Columns.Add("Tài khoản");
                lv_Account_List.Columns.Add("Mật khẩu");
                lv_Account_List.Columns.Add("Cookie");
                lv_Account_List.Columns.Add("Email");
                lv_Account_List.Columns.Add("Website");
                lv_Account_List.Columns.Add("Trạng thái");


                foreach (taikhoan tk in lst_taikhoan)
                {
                    if (tk.tendangnhap != null)
                    {
                        ListViewItem item = new ListViewItem();
                        item.Text = stt.ToString();
                        item.SubItems.Add(tk.id.ToString());
                        item.SubItems.Add(tk.tendangnhap);
                        item.SubItems.Add(tk.matkhau);
                        item.SubItems.Add(tk.cookie);
                        item.SubItems.Add(tk.email);
                        website w = website.websiteSelectRow(tk.websiteid);
                        item.SubItems.Add(w.link);
                        if (tk.trangthai == 1)
                            item.SubItems.Add("Đang hoạt động");
                        if (tk.trangthai != 1)
                            item.SubItems.Add("Die");
                        Button btn_view = new Button();
                        lv_Account_List.Items.Add(item);
                        stt++;
                    }
                }
                pb_TaskProccess.Minimum = 0;
                pb_TaskProccess.Maximum = lst_taikhoan.Count;
                pb_TaskProccess.Value = 0;
                pb_TaskProccess.Step = 1;
            }
        }

        public void Login()
        {
            int index = 0;
            foreach (taikhoan tk in lst_taikhoan)
            {
                m_log.Info(index.ToString());
                tk.cookie = null;
                chitietnghiepvu nghiepvu = chitietnghiepvu.chitietnghiepvuSelectRowByForeignKey_nghiepvuid_websiteid(2, tk.websiteid).SingleOrDefault();
                LoginTask t = new LoginTask(nghiepvu, index.ToString());
                t.TimeToRepeat = 0;
                t.m_tk = tk;
                
                t.onFinished += this.onFinished;
                t.onError += this.onError;
                if (tk == null || tk.tendangnhap == null || tk.matkhau == null)
                {
                    onError(t, index);
                    m_log.Warn("Khong co ten dang nhap");
                    index++;
                    continue;
                }
                // FAP.DataAccess.FAPDataContext context = new FAP.DataAccess.FAPDataContext();
                {

                    //chitietnghiepvu nghiepvu = context.chitietnghiepvus.Where(m => m.website.id == tk.websiteid && m.nghiepvuid == 2).SingleOrDefault();

                    if (nghiepvu == null)
                    {
                        onError(t, index);
                        m_log.Warn("Khong co chi tiet nghiep vu dang nhap");
                        index++;
                        continue;
                    }
                    var lstBTH = buocthuchien.buocthuchienSelectRowByForeignKey_chitietnghiepvuid(nghiepvu.id);
                    if (lstBTH.Count == 0)
                    {
                        onError(t, index);
                        m_log.Warn("Khong co buoc thuc hien");
                        index++;
                        continue;
                    }

                    //t.RunIt();
                    FAP.Cores.Threading.ThreadControl.AddTasks(t);
                    index++;
                }
            }

        }
        public bool CheckResultLogin(string html, taikhoan tk)
        {
            html = html.ToLower();
            if (html.Contains("logout") == true)
                return true;
            if (html.Contains("đăng xuất") == true)
                return true;
            if (html.Contains("đăng nhập thành công") == true)
                return true;
            if (html.Contains("chúc mừng") == true)
                return true;
            if (html.Contains("xin chào") == true)
                return true;
            if (html.Contains("cảm ơn") == true)
                return true;
            if (html.Contains("cám ơn") == true)
                return true;
            if (html.Contains("đã đăng nhập") == true)
                return true;
            if (html == "")
                return true;
            if (html.Contains(tk.tendangnhap) == true)
                return true;
            return false;
        }
        public void onFinished(object sender, object result)
        {
            //FAPDataContext context = new FAPDataContext();
            //FAP.Cores.Requesting.Requester requester = new FAP.Cores.Requesting.Requester();
            LoginTask t = (LoginTask)sender;
            taikhoan tk = t.m_tk;
            var datapost = t.DataPost;
            string html = t.LastHTML;
            //if (html == "")
            //{
            //    string strLink = t.requester.uri.AbsoluteUri.Substring(0, t.requester.uri.AbsoluteUri.IndexOf(":"));
            //    var resp = t.requester.GetData(strLink + "://" + t.requester.uri.Host);
            //    string htmls = t.requester.GetHtmlFromResponse(resp);
            //    t.LastHTML = htmls;
            //    html = t.LastHTML;
            //    t.response = resp;
            //}
            if (CheckResultLogin(html, tk) == true && t.response != null)
            {
                var response = (HttpWebResponse)t.response;
                string cookieheader = "";
                //foreach (Cookie cookie in t.requester.Cookie)
                {
                    //Console.WriteLine(cookie.Name + " = " + cookie.Value);
                    cookieheader = t.requester.Cookie;
                }
                if (string.IsNullOrEmpty(cookieheader) == false)
                {
                    //cookieheader = cookieheader.Remove(cookieheader.Length - 1, 1);
                    tk.cookie = cookieheader;
                    tk.trangthai = 1;
                    taikhoan.taikhoanUpdateRow(tk.id, tk.tendangnhap, tk.matkhau, tk.email, tk.cookie, tk.ngayhethan, tk.websiteid, tk.trangthai, tk.isdeleted);
                    m_log.Info("Dang nhap thanh cong.");
                    this.Invoke((MethodInvoker)delegate
                    {
                        pb_TaskProccess.PerformStep();
                        lbl_Percent.Text = "Đã đăng nhập" + pb_TaskProccess.Value.ToString() + "/" + pb_TaskProccess.Maximum;
                        lv_Account_List.Items[int.Parse(t.m_index)].BackColor = Color.LemonChiffon;
                        lv_Account_List.Items[int.Parse(t.m_index)].SubItems[4].Text = tk.cookie;
                        if (tk.trangthai == 1)
                            lv_Account_List.Items[int.Parse(t.m_index)].SubItems[7].Text = "Đang hoạt động";
                        else
                        {
                            lv_Account_List.Items[int.Parse(t.m_index)].SubItems[7].Text = "Không đăng nhập được";
                            lv_Account_List.Items[int.Parse(t.m_index)].BackColor = Color.Lavender;
                        }
                    });
                }


            }
            else
            {
                m_log.Info("Dang nhap that bai vui long xem HTML!");
                tk.cookie = "";
                tk.trangthai = 0;
                taikhoan.taikhoanUpdateRow(tk.id, tk.tendangnhap, tk.matkhau, tk.email, tk.cookie, tk.ngayhethan, tk.websiteid, tk.trangthai, tk.isdeleted);
                System.IO.StreamWriter file = new System.IO.StreamWriter(tk.websiteid.ToString() + "_" + tk.tendangnhap + "_" + tk.matkhau + ".html");
                m_log.Info(file.ToString());
                file.WriteLine(html);
                file.Close();
                website w = website.websiteSelectRow(tk.websiteid);
                m_log.Info("Dang nhap khong thanh cong " + tk.tendangnhap + "/" + w.link);
                this.Invoke((MethodInvoker)delegate
                {
                    pb_TaskProccess.PerformStep();
                    lbl_Percent.Text = "Đã đăng nhập" + pb_TaskProccess.Value.ToString() + "/" + pb_TaskProccess.Maximum;
                    lv_Account_List.Items[int.Parse(t.m_index)].BackColor = Color.Lavender;
                    lv_Account_List.Items[int.Parse(t.m_index)].SubItems[7].Text = "Không đăng nhập được";
                    lv_Account_List.Items[int.Parse(t.m_index)].SubItems[4].Text = tk.cookie;
                });
            }

        }

        public void onError(object sender, object result)
        {
            //Quăng lỗi

            this.Invoke((MethodInvoker)delegate
            {
                pb_TaskProccess.PerformStep();
                LoginTask task = (LoginTask)sender;

                int index = int.Parse(task.m_index);
                lbl_Percent.Text = "Đã đăng nhập" + pb_TaskProccess.Value.ToString() + "/" + pb_TaskProccess.Maximum;
                lv_Account_List.Items[index].BackColor = Color.Lavender;
                lv_Account_List.Items[index].SubItems[7].Text = "Không đăng nhập được | ";
            });

        }



        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            this.Refresh();
        }


        private void btn_LoginAll_Click_2(object sender, EventArgs e)
        {
            pb_TaskProccess.Value = 0;
            proccess_percent = 0;
            this.Login();
        }

        private void gv_AccountList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void viewHTML_Click(object sender, EventArgs e)
        {
            if (lv_Account_List.SelectedIndices.Count == 1)
            {
                taikhoan tk = lst_taikhoan[lv_Account_List.SelectedIndices[0]];
                string pathToHtmlFile = tk.websiteid + "_" + tk.tendangnhap + "_" + tk.matkhau + ".html";
                try
                {
                    System.Diagnostics.Process.Start(pathToHtmlFile);
                }
                catch (Exception ex)
                {
                    m_log.Warn("Khong tim duoc file HTML");
                    MessageBox.Show("Thông báo: đã đăng nhập thành công", "Đăng nhập đã thành công.");

                }
            }
        }

        private void ucLogin_Load(object sender, EventArgs e)
        {
            if (Process.GetCurrentProcess().ProcessName == "devenv")
                return;
            List<taikhoan> lst_taikhoan = new List<taikhoan>();
            this.Refresh();

        }





    }
}
